package com.xiaxueqi.web.home;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.niagara.context.SecurityContext;
import com.niagara.dao.Page;
import com.niagara.security.auth.entity.UserDetail;
import com.niagara.service.base.BaseService;
import com.niagara.web.struts2.CRUDActionSupport;
import com.niagara.web.struts2.Struts2Utils;
import com.xiaxueqi.entity.book.AppFavorite;

@Results( { @Result(name = CRUDActionSupport.RELOAD, location = "friends.action", type = "redirect") })
public class FriendsAction extends CRUDActionSupport<AppFavorite> {
	private static final long serialVersionUID = 1L;

	@Autowired
	private BaseService baseService;
	private AppFavorite entity;
	private Integer id;
	private Page<AppFavorite> page;

	private UserDetail detail = SecurityContext.getUserDetail();
	private Integer userId = detail != null ? Integer.valueOf(detail
			.getUserId().intValue()) : null;
	private Integer addUserId;

	@Override
	public String delete() throws Exception {
		this.entity = this.baseService.get(AppFavorite.class, this.id);
		this.entity.setDeleted("Y");
		this.baseService.update(this.entity);
		return RELOAD;
	}

	@Override
	public String list() throws Exception {
		return SUCCESS;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (this.id != null) {
			this.entity = this.baseService.get(AppFavorite.class, this.id);
		} else {
			this.entity = new AppFavorite();
		}
	}

	@Override
	public String save() throws Exception {
		if (entity.getId() == null) {
			baseService.insert(entity);
		} else {
			baseService.update(entity);
		}
		addActionMessage("保存成功");
		return RELOAD;
	}

	public AppFavorite getModel() {
		return this.entity;
	}

	public String add() throws Exception {
		this.entity = new AppFavorite();
		entity.setFavoriteId(this.addUserId);
		AppFavorite tempEntity = this.baseService.get(AppFavorite.class,
				entity, "select_by_condition");
		entity.setDeleted("N");
		entity.setFavoriteType("user");
		entity.setOwnerId(userId);
		if (tempEntity == null) {
			baseService.insert(entity);
		} else {
			Struts2Utils.renderText("对不起，此用户已经是您关注的朋友！");
		}

		return NONE;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Page<AppFavorite> getPage() {
		return page;
	}

	public Integer getUserId() {
		return userId;
	}

	public Integer getAddUserId() {
		return addUserId;
	}

	public void setAddUserId(Integer addUserId) {
		this.addUserId = addUserId;
	}
}
